'''
Created on 2016年2月22日

@author: Administrator
'''
from asyncore import dispatcher
from asynchat import async_chat
import asyncore, socket

PORT = 5005



class ChatSession(async_chat):
    
    def __init__(self, sock):
        async_chat.__init__(self, sock)
        self.set_terminator(b'\r\n')
        self.data = []
        
    def collect_incoming_data(self, data):
        self.data.append(data.decode('utf-8', 'ignore'))
        #self.data.append(data)
        
    def found_terminator(self):
        line = ''.join(self.data)
        self.data = []
        pass # 处理这行数据
        print(line)
        #line += b'\r\n'
        self.push(line.encode('utf_8', 'strict'))


class ChatServer(dispatcher):
    def __init__(self, port):
        dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(('', port))
        self.set_reuse_addr()
        self.listen(5)
        self.sessions = []
        
            
    def broadcast(self, line):
        for session in self.sessions:
            session.push(line + '\r\n')
        
    def handle_accept(self):
        conn, addr = self.accept()
        self.sessions.append(ChatSession(conn))
        print('connection attempt from ', addr[0])
        

if __name__ == '__main__':
    s = ChatServer(PORT)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        print